package org.bhf.providers.security.authentication.mysql;

import org.bhf.db.migration.Migration;
import org.bhf.db.migration.Util;
import org.bhf.facilities.ProjectConfiguration;
import org.bhf.providers.security.authentication.Role;
import org.bhf.providers.security.authentication.RoleMap;
import org.bhf.providers.security.authentication.User;
import org.bhf.security.util.Crypto;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import java.io.IOException;
import java.util.Date;

public class Migrate0 implements Migration
{
    final static String scriptBase = Migrate0.class.getPackage().getName().replace( '.', '/' ) + "/";

    public void upTo( final EntityManager entityManager )
        throws IOException, PersistenceException
    {
        Util.executeStatements( entityManager, scriptBase + "0.do.sql" );

        {
            final User user = new User();

            user.setId( "449-23-9825" );
            user.setGroup( "acme.c4" );
            user.setFirstName( "William" );
            user.setLastName( "Connor" );
            user.setNickName( "Bill" );
            user.setEmail( "charlieo@blueholesoftware.com" );

            user.setLoginID( "foo" );
            user.setPasswordHash( Crypto.encodeMD5Base64( "passw0rd" ) );
            user.setExpires( new Date( System.currentTimeMillis() + 60 * 1000L ) );

            {
                final Role      r   = new Role();
                final RoleMap   rm  = new RoleMap();

                rm.setProject( "proj" );
                r.setName( "admin" );

                entityManager.persist( r );

                rm.setRole( r );

                user.getRoleMap().add( rm );
            }

            entityManager.persist( user );
        }

        {
            final ProjectConfiguration c = new ProjectConfiguration();

            c.setName( org.bhf.providers.security.authentication.Provider.class.getName() );
            c.setPath( "foo" );
            c.setValue( "{sessionLengthInMinutes:1,strikeOutCount:1,strikeOutHoldInSeconds:1,minimumPasswordLength:1,passwordPattern:\"\",passwordValidityInDays:1}" );
            
            entityManager.persist( c );
        }

        {
            final ProjectConfiguration c = new ProjectConfiguration();

            c.setName( org.bhf.providers.security.authentication.Provider.class.getName() );
            c.setPath( "tres" );
            c.setValue( "{strikeOutCount:3,strikeOutHoldInSeconds:5}" );

            entityManager.persist( c );
        }
    }

    public void downFrom( final EntityManager entityManager )
        throws IOException, PersistenceException
    {
        Util.executeStatements( entityManager, scriptBase + "0.undo.sql" );
    }
}